package com.wey.springboot.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wey.springboot.bean.QuartzTask;
import com.wey.springboot.service.MessageRemindService;
import com.wey.springboot.util.CommonResult;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class MessageRemindController {
  @Autowired
  private MessageRemindService taskService;

  @GetMapping("/messageRemind/list")
  public CommonResult<List<QuartzTask>> getList(@RequestParam("groupName") String groupName) {
    QueryWrapper<QuartzTask> wrapper = new QueryWrapper<>();
    wrapper.eq("group_name", groupName);
    List<QuartzTask> list = taskService.list(wrapper);
    return CommonResult.success(list);
  }

  @GetMapping("/messageRemind/start")
  public CommonResult<Integer> loadJob(@RequestParam("id") Integer id) {
    try {
      taskService.startTask(id);
    } catch (SchedulerException e) {
      return CommonResult.fail("任务启动失败");
    }
    return CommonResult.success(1, "任务启动成功");
  }

  @GetMapping("/messageRemind/stop")
  public CommonResult<Integer> stopJob(@RequestParam("id") Integer id) {
    try {
      taskService.stopTask(id);
    } catch (SchedulerException e) {
      return CommonResult.fail("任务停止失败");
    }
    return CommonResult.successMsg("任务停止成功");
  }

  @PostMapping("/messageRemind/add")
  public CommonResult<Integer> addTask(@RequestBody QuartzTask quartzTask) {
    System.out.println(quartzTask);
    taskService.save(quartzTask);
    return CommonResult.success(1, "任务添加成功");
  }

  @GetMapping("/messageRemind/delete")
  public CommonResult<Integer> addTask(@RequestParam("id") Integer id) {
    try {
      taskService.deleteTask(id);
    } catch (SchedulerException e) {
      return CommonResult.fail("任务删除失败");
    }
    return CommonResult.success(1, "任务删除成功");
  }

  @PostMapping("/messageRemind/update")
  public CommonResult<Integer> updateTask(@RequestBody QuartzTask quartzTask) {
    try {
      taskService.updateTask(quartzTask);
    } catch (SchedulerException e) {
      return CommonResult.fail("任务更新失败");
    }
    return CommonResult.success(1, "任务更新成功");
  }
}
